package com.lbkj.wsc;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.List;

public class WSCResult {

    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public <T> T toBean(Class<T> clazz) {
        return XmlUtils.xmlToBean(data, clazz);
    }

    public WSCMap toWSCMap() {
        Document document = null;
        try {
            document = DocumentHelper.parseText(data);
        } catch (Exception e) {
            throw new WSCException("XML格式错误", e);
        }
        // rtn
        List<Element> elements = document.getRootElement().elements();
        WSCMap map = new WSCMap();
        if(elements.isEmpty()) {
            return map;
        }
        _recur_parse(elements, map);
        return map;
    }

    private void _recur_parse(List<Element> elements, WSCMap map) {
        for(Element element: elements){
            // 子元素
            final List<Element> children_el_list = element.elements();
            if(children_el_list.isEmpty()) {
                map.put(element.getName(), element.getText());
            } else {
                WSCMap children_map = new WSCMap();
                map.put(element.getName(), children_map);
                _recur_parse(children_el_list, children_map);
            }
        }
    }

    @Override
    public String toString() {
        return "WSCResult{" +
                "data='" + data + '\'' +
                '}';
    }
}
